package com.auto.learning.activity;

import java.io.IOException;
import java.io.InputStream;

import com.auto.learning.tools.FileHelper;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.net.http.SslError;
import android.os.Build;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * 自定义WebViewClient
 */
public abstract class BaseWebViewClient extends WebViewClient {

    /**
     * Report an error to the host application
     * 
     * @param view webview
     * @param errorCode 详看：WebViewClient.ERROR_*
     * @param description 错误描述
     * @param failingUrl 产生错误的url
     * @author yansu
     */
    public abstract void receivedError(WebView view, int errorCode, String description,
            String failingUrl);

    /**
     * ssl certificate error request
     * 
     * @param view webview
     * @param handler An SslErrorHandler object that will handle the user's
     *            response.
     * @param error The SSL error object
     * @author yansu
     */
    public abstract void receivedSslError(WebView view, SslErrorHandler handler, SslError error);

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
    	
        int idx = url.indexOf("returnHome:");
        if (idx != -1) {
            Context ctx;
            Activity activity = (Activity) view.getTag(view.getId());
            if (activity != null) {
                ctx = activity;
            } else {
                ctx = view.getContext();
            }
            String method = url.substring(0, idx + 1);
//            Processor processor = ProcessorFactory.createProcessor(method, ctx);        
//            
            if (null != mOnCustomerUrlLoadingListener) {
            	mOnCustomerUrlLoadingListener.onCustomerUrlLoading(view, url);
                return true;
            }
            
        }
        return super.shouldOverrideUrlLoading(view, url);
    }

    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        receivedError(view, errorCode, description, failingUrl);
        super.onReceivedError(view, errorCode, description, failingUrl);
    }

    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
        // TODO Auto-generated method stub
        receivedSslError(view, handler, error);
        super.onReceivedSslError(view, handler, error);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
        WebResourceResponse ret = super.shouldInterceptRequest(view, url);
        if (ret == null
                && (url.contains("?") || url.contains("#") || needsIceCreamSpaceInAssetUrlFix(url))) {
            ret = generateWebResourceResponse((Activity) view.getTag(view.getId()), url);
        }
        return ret;
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private WebResourceResponse generateWebResourceResponse(Activity activity, String url) {
        if (url.startsWith("file:///android_asset/")) {
            String mimetype = FileHelper.getMimeType(url, activity);
            try {
                InputStream stream = FileHelper.getInputStreamFromUriString(url, activity);
                WebResourceResponse response = new WebResourceResponse(mimetype, "UTF-8", stream);
                return response;
            } catch (IOException e) {
            }
        }
        return null;
    }

    private static boolean needsIceCreamSpaceInAssetUrlFix(String url) {
        if (!url.contains("%20")) {
            return false;
        }

        switch (android.os.Build.VERSION.SDK_INT) {
            case android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH:
           // case android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1:
                return true;
            default:
                return false;
        }
    }

    private OnCustomerUrlLoadingListener mOnCustomerUrlLoadingListener=null;
    
    public void addOnCustomerUrlLoadingListener(OnCustomerUrlLoadingListener onCustomerUrlLoadingListener){
    	mOnCustomerUrlLoadingListener=onCustomerUrlLoadingListener;
    }
    
    public interface OnCustomerUrlLoadingListener{
    	public void onCustomerUrlLoading(WebView view, String url);
    }
    
    
}
